package cn.wolfcode.wms.web.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.wolfcode.wms.domain.SystemMenu;
import cn.wolfcode.wms.query.SystemMenuQueryObject;
import cn.wolfcode.wms.service.ISystemMenuService;
import cn.wolfcode.wms.util.JsonResult;
import cn.wolfcode.wms.util.RequiredPermission;

@Controller
@RequestMapping("/systemmenu")
public class SystemMenuController {
	@Autowired
	private ISystemMenuService service;
	
	@RequestMapping("/list")
	@RequiredPermission("系统菜单列表")
	public String list(Model model,@ModelAttribute("qo")SystemMenuQueryObject qo){
		model.addAttribute("result", service.query(qo));
		List<SystemMenu> parents = new ArrayList<SystemMenu>();
		//根据parentId查询 父菜单
		SystemMenu parent = service.get(qo.getParentId());
		while (parent!=null) {
			parents.add(parent);
			//不调用getParent()方法时  不会触发延时加载
			parent = parent.getParent();
		}
		Collections.reverse(parents);
		model.addAttribute("parents", parents);
		return "systemmenu/list";
	}
	@RequestMapping("/delete")
	@ResponseBody
	@RequiredPermission("系统菜单删除")
	public JsonResult delete(Long id){
		JsonResult result = new JsonResult();
		try {
			if (id!=null) {
				service.delete(id);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.markMsg("亲,请先删除下级菜单,才能删除此菜单");
		}
		return result;
	}
	
	@RequiredPermission("系统菜单编辑")
	@RequestMapping("/input")
	public String input(Long id,Long parentId,Model model){
		if (id!=null) {
			model.addAttribute("menu", service.get(id));
		}
		if (parentId==null) {
			model.addAttribute("parentName", "根目录");
		}else{
			SystemMenu menu = service.get(parentId);
			model.addAttribute("parentName", menu.getName());
			model.addAttribute("parentId", menu.getId());
		}
		return "systemmenu/input";
	}
	@RequiredPermission("系统菜单保存或更新")
	@RequestMapping("/saveOrUpdate")
	public String saveOrUpdate(SystemMenu systemmenu){
		if (systemmenu.getId()!=null) {
			service.update(systemmenu);
		}else{
			service.save(systemmenu);
		}
		if (systemmenu.getParent().getId()!=null) {
			return "redirect:/systemmenu/list?parentId="+systemmenu.getParent().getId();
		}
		return "redirect:/systemmenu/list";
	}
	@RequiredPermission("系统菜单加载")
	@RequestMapping("/selectByParentSn")
	@ResponseBody
	public  List<Map<String, Object>> selectByParentSn(String parentSn){
		return service.selectByParentSn(parentSn);
	}
	
}
